#include "gpioSwitch.h"

void switch_set(int pin,enum switchState _state)
{
	switch(_state)
	{
		case ON:
			digitalWrite(pin,HIGH);
			D_PRINTF("The io is set HIGH\n");
			break;
		case OFF:
			digitalWrite(pin,LOW);
			D_PRINTF("The io is set LOW\n");
			break;
		default:
			break;
	}

}
void *switch_handle(void *arg)
{
	struct thread_data_t data = *(struct thread_data_t *)arg;

    switchState swSta = data.state;
    if(data.mode == modeDelay)
    {
        sleep(data.seconds);
        switch_set(data._pin,swSta);
        pthread_exit(NULL);
    }
    else if(data.mode == modeCycle)
    {
        
        while(1)
        {
            switch_set(data._pin,swSta);
            sleep(data.seconds);

            if(swSta == ON)
                swSta = OFF;
            else
                swSta = ON;
        }
    }
}
gpioSwitch::gpioSwitch(int _pin)
{
	pin = _pin;

	if(wiringPiSetup() < 0)
	{
		perror("setup");
	}
	
	//初始化引脚为输出模式
	pinMode(pin,OUTPUT);

	D_PRINTF("The io has been init to output mode\n");

	thread_data._pin = pin;
	
}
gpioSwitch::~gpioSwitch()
{

}
int gpioSwitch::set(enum switchState _state)
{
	switch_set(pin,_state);
}
int gpioSwitch::set(enum switchState _state,int seconds)
{
    thread_data.mode = modeDelay;
	thread_data.seconds = seconds;
	thread_data.state = _state;

//	pthread_attr_init(&switch_thread_attr);
//	pthread_attr_setdetachstate(&switch_thread_attr,PTHREAD_CREATE_DETACHED);


	if(pthread_create(&switch_thread,NULL,switch_handle,(void *)&thread_data) != 0)
	{
		perror("pthread create");
	}
	
	pthread_join(switch_thread,NULL);

}
int gpioSwitch::setCycle(int _time)
{
    thread_data.mode = modeCycle;
    thread_data.seconds = _time;
	thread_data.state = ON;

	if(pthread_create(&switch_thread,NULL,switch_handle,(void *)&thread_data) != 0)
	{
		perror("pthread create");
	}
	
	pthread_join(switch_thread,NULL);
}
